package com.tsfyun.scm.config;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.tsfyun.common.base.constant.BaseContextConstant;
import com.tsfyun.common.base.dto.CommonData;
import com.tsfyun.common.base.util.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;

/**=
 * fegin客户端配置
 */
@Slf4j
@Configuration
public class FeiginConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return;
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        List<String> headNameList = Lists.newArrayList();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                headNameList.add(name);
                if(CommonData.forwardHeaderNames.contains(name)){
                    Enumeration<String> values = request.getHeaders(name);
                    while (values.hasMoreElements()) {
                        String value = values.nextElement();
                        requestTemplate.header(name, value);
                    }
                }
            }
        }

        if(!headNameList.contains(BaseContextConstant.HTTP_HEADER_TRACE_ID)) {
            //增加日志追踪id传递
            String logTraceId = MDC.get(BaseContextConstant.LOG_TRACE_ID);
            String traceId = StrUtil.isNotEmpty(logTraceId)  ?  logTraceId :  MDC.get(BaseContextConstant.LOG_B3_TRACEID) ;
            if (StrUtil.isNotEmpty(traceId)) {
                requestTemplate.header(BaseContextConstant.HTTP_HEADER_TRACE_ID, traceId);
            }
        }
    }
}
